package com.xcity.game.task.detector;

import com.alibaba.fastjson.JSONArray;
import com.xcity.game.task.Task;
import com.xcity.game.task.Task.State;
import com.xcity.game.task.TaskDetector;
import com.xcity.game.task.TaskDetectorLabel;

/**
 * <pre>
 * 掠夺任务
 * 2个参数:
 * 1.结果(0:失败,1:成功,2:成功或失败)
 * 2.抢劫/掠夺次数
 * </pre>
 * @author yang.li
 *
 */
@TaskDetectorLabel(TaskDetector.ATTACK_BUILD)
public class BuildAttackTaskDetector implements TaskDetector {

	static final String KEY = String.valueOf(ATTACK_BUILD);
	
	@Override
	public boolean isFinish(Task task) {
		if (task.getTemplate().getConditionId() != ATTACK_BUILD) {
			return false;
		}
		if (task.getState() == State.FINISHED || task.getState() == State.REWARDED) {
			return true;
		}
		JSONArray data = task.getArchive().getJSONArray(KEY);
		if (data == null) {
			return false;
		}
		int[] conds = task.getTemplate().getConditions();
		int result = conds[0];
		int num = conds[1];
		if (result == 2) { // 成功、失败都计算
			return getSafely(data, 0) + getSafely(data, 1) >= num;
		}
		return getSafely(data, result) >= num;
	}

	@Override
	public void onArchive(Task task, Object... vals) {
		boolean succ = ((Number) vals[3]).intValue() > 0; // EVENT_ATTACK_BUILD: 表示获得现金数, EVENT_ATTACK_BUILD_V2: 表示结果
		// { 2: [fail num, succ num] }
		JSONArray data = task.getArchive().getJSONArray(KEY);
		if (data == null) {
			data = new JSONArray(2);
			data.add(0);
			data.add(0);
			task.getArchive().put(KEY, data);
		}
		int index = succ ? 1 : 0;
		data.set(index, getSafely(data, index) + 1);
	}
	
	static int getSafely(JSONArray data, int index) {
		return index >= 0 && index < data.size() ? data.getIntValue(index) : 0;
	}

}
